package cate.game.pvp.eliterace;

import cate.game.GameBody;
import cate.game.db.SaveConstants;
import cate.game.framework.ModuleMan;
import cate.game.pvp.eliterace.handler.EliteRaceHandler;
import cate.game.pvp.eliterace.handler.LocalEliteRaceHandler;
import cate.game.util.IntervalCounter;
import lombok.Getter;

import static cate.game.pvp.eliterace.handler.EliteRaceHandler.ofLocal;

public class EliteRaceManager extends ModuleMan {

    public static final String MODULE_NAME = "elite-race";

    @Getter
    private final EliteRaceDataManager dataManager = new EliteRaceDataManager();
    @Getter
    private final EliteRaceSimulatorManager simulatorManager
            = new EliteRaceSimulatorManager(
            this.getDataManager()::getData,
            this.getDataManager()::getPsOperation,
            this.getDataManager()::getRecordOperation,
            this.getDataManager()::getFightOperation,
            this.getDataManager()::getRankRwdOperation,
            this.getDataManager()::getBetOperation,
            this.getDataManager()::getRankHandler,
            this.getDataManager()::getExcelQueryOperation,
            this.getDataManager()::getVideoOperation
    );
    private final EliteRaceTimerModule timerModule
            = new EliteRaceTimerModule(
            this::getDataManager,
            this::getSimulatorManager
    );

    private LocalEliteRaceHandler localHandler;


    public EliteRaceHandler getHandler() {
        return this.localHandler;
    }

    @Override
    public void initIndependent(GameBody game) throws Exception {
        super.initIndependent(game);
        this.dataManager.initIndependent(game);
        this.simulatorManager.initIndependent(game);
        this.timerModule.initIndependent(game);
    }

    @Override
    public void initDependent() throws Exception {
        this.dataManager.initDependent();
        this.simulatorManager.initDependent();
        this.localHandler = ofLocal(game);
        this.timerModule.initDependent();
    }

    private final IntervalCounter saveTrigger = new IntervalCounter(SaveConstants.PVP_SAVE_SECONDS);

    public void tick() {
        this.timerModule.tick();
        if (saveTrigger.trigger()) {
            this.dataManager.save();
        }
    }


    @Override
    public void shutdown() {
        super.shutdown();
        this.timerModule.shutdown();
        this.simulatorManager.shutdown();
        this.dataManager.shutdown();
    }
}
